package org.university.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.university.dto.request.RegisterStudentRequestDTO;
import org.university.dto.request.RegisterTeacherRequestDTO;
import org.university.exception.BusinessValidationException;

import java.util.regex.Pattern;

/**
 * 有效性验证工具
 */
public class ValidationUtils {

    private static final Logger logger = LoggerFactory.getLogger(ValidationUtils.class);
    private static final String EMAIL_REGEX = "^[\\w+&*-]+(?:\\.[\\w+&*-]+)*@(?:[\\w-]+\\.)+[a-zA-Z]{2,7}$";
    private static final String PASSWORD_REGEX = "^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,}$";

    public static boolean isValidEmail(String email) {
        if (email == null) return false;
        return Pattern.compile(EMAIL_REGEX).matcher(email).matches();
    }

    public static boolean isStrongPassword(String password) {
        if (password == null) return false;
        return Pattern.compile(PASSWORD_REGEX).matcher(password).matches();
    }

    public static void validateUser(RegisterStudentRequestDTO user) {
        logger.info("正在检测注册学生：{}", user);
        if (user == null) {
            throw new BusinessValidationException("注册学生对象不能为空");
        }
        if (!isValidEmail(user.getEmail())) {
            throw new BusinessValidationException("邮箱格式无效");
        }
        if (!isStrongPassword(user.getPassword())) {
            throw new BusinessValidationException("密码需包含大小写字母、数字和特殊字符");
        }
    }

    public static void validateUser(RegisterTeacherRequestDTO user) {
        logger.info("正在检测注册教师：{}", user);
        if (user == null) {
            throw new BusinessValidationException("注册教师对象不能为空");
        }
        if (!isValidEmail(user.getEmail())) {
            throw new BusinessValidationException("邮箱格式无效");
        }
        if (!isStrongPassword(user.getPassword())) {
            throw new BusinessValidationException("密码需包含大小写字母、数字和特殊字符");
        }
    }
}